//
//  PublishViewController.swift
//  NSinaWeibo
//
//  Created by LoliQueen on 16/2/25.
//  Copyright © 2016年 LoliQueen. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

class PublishViewController: UIViewController {
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        
        setNavBar()
        setTextView()
        setToolBar()
        registerNotification()
        
        setPicture()
        
        
    }
    
//    func actionName(){
//        //更新图片视图的高度
//        pictureController.view.snp_updateConstraints { (make) -> Void in
//            make.height.equalTo(ScreenHeight/3*2)
//        }
//        //更新视图
//        UIView.animateWithDuration(0.25) { () -> Void in
//            self.view.layoutIfNeeded()
//        }
//    }
    
    //注册通知，监听键盘的弹出还是收起
    private func registerNotification(){
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyBoardChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    //移除通知
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    /*NSConcreteNotification 0x7f81d0e80280 {name = UIKeyboardDidChangeFrameNotification; userInfo = {
    UIKeyboardAnimationCurveUserInfoKey = 7;
    UIKeyboardAnimationDurationUserInfoKey = "0.25";
    UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {414, 271}}";
    UIKeyboardCenterBeginUserInfoKey = "NSPoint: {207, 600.5}";
    UIKeyboardCenterEndUserInfoKey = "NSPoint: {207, 871.5}";
    UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 465}, {414, 271}}";
    UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 736}, {414, 271}}";
    UIKeyboardIsLocalUserInfoKey = 1;
    }}
    NSConcreteNotification 0x7f81d0c1b1a0 {name = UIKeyboardDidChangeFrameNotification; userInfo = {
    UIKeyboardAnimationCurveUserInfoKey = 7;
    UIKeyboardAnimationDurationUserInfoKey = "0.25";
    UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {414, 271}}";
    UIKeyboardCenterBeginUserInfoKey = "NSPoint: {207, 871.5}";
    UIKeyboardCenterEndUserInfoKey = "NSPoint: {207, 871.5}";
    UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 736}, {414, 271}}";
    UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 736}, {414, 271}}";
    UIKeyboardIsLocalUserInfoKey = 1;
    }}*/
    //监听通知执行的方法
   @objc private func keyBoardChange(n:NSNotification){
    //获取键盘 弹出所用时间 转化成nsnumber才能添加到字典中
    let duration = (n.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
    //键盘结束的frame ，CGRect 转换成NSValue 才能添加到字典中
    let rect = (n.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
    
    print(rect.origin.y)
    
    ////origin 是什么？？？？？
    let height = -ScreenHeight + rect.origin.y
    //在动画闭包中，更新UI
    UIView.animateWithDuration(duration){ () -> Void in
        self.toolBar.snp_updateConstraints(closure: { (make) -> Void in
            make.bottom.equalTo(height)
        })
        
        //强制刷新视图
        self.view.layoutIfNeeded()
    }
//        print(n)
    }
    
    ///懒加载站位文本textView视图
    private lazy var textView: UITextView = {
        let tv = UITextView()
        //        tv.text = "输入新鲜事..."
        tv.font = UIFont.systemFontOfSize(16)
        tv.textColor = UIColor.lightGrayColor()
        //设置代理
        tv.delegate = self
        tv.backgroundColor = UIColor.brownColor()
        
        //在竖直滚动时 Bounce弹回键盘
        tv.alwaysBounceVertical = true
        //在滚动的时候让键盘消失。在iOS7.0出现的。因为textView是继承UIscrollerView 可以滚动，只有在可以滚动的视图中才有效果
        tv.keyboardDismissMode = .OnDrag
        return tv
        }()
    ///懒加载站位文本，监听是否哟怒诶荣，从而改变发布按钮的状态
    private lazy var placeHolder : UILabel = UILabel(title: "输入新鲜事...", textSize: 16, textColor: UIColor.lightGrayColor())
    //懒加载toolbar
    private lazy var toolBar : UIToolbar = UIToolbar()
    
    //图片视图控制器
    private lazy var pictureController = PictureSelectedViewController()
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
}


///设置UI的相关分类
extension PublishViewController{
    
    private func setPicture(){
        //1、添加视图控制器，
        self.addChildViewController(pictureController)
        //2、添加视图控制器的视图
        view.addSubview(pictureController.view)
        //3、将toolbar移到最顶层
        self.view.bringSubviewToFront(toolBar)
        //4、添加约束
        pictureController.view.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(view.snp_bottom)
            make.height.equalTo(0)
        }
    }
    ///自定义导航条
    private func setNavBar(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .Plain, target: self, action: "send")
        
        //开始设置发布按钮不能交互
        navigationItem.rightBarButtonItem?.enabled = false
        
        //自定义导航条的title
        let weiboTitle : UILabel = UILabel(title: "发布微博", textSize: 18, textColor: UIColor.darkGrayColor())
        let nameTitle : UILabel = UILabel(title: AccountViewModel.shareAccountViewModel.userName ?? "" , textSize: 14, textColor: UIColor.lightGrayColor())
        
        //    navigationItem.titleView 默认为nil 为了显示，必须赋值
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 375, height: 40))
        
        navigationItem.titleView = titleView
        //设置控件位置
        titleView.addSubview(weiboTitle)
        titleView.addSubview(nameTitle)
        weiboTitle.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(titleView.snp_top)
            make.centerX.equalTo(titleView.snp_centerX)
        }
        nameTitle.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(weiboTitle.snp_bottom)
            make.centerX.equalTo(titleView.snp_centerX)
        }
        
    }
    
    @objc func close(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    ///使用接口发布微博
    @objc func send(){
        print(__FUNCTION__)
        //发送文本微博
        var urlString = "2/statuses/update.json"
        //status 发布微博的内容
        let parameters = ["access_token": AccountViewModel.shareAccountViewModel.access_token,"status":textView.text]
        if pictureController.imageList.count > 0{
            //发送图片微博
             urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            //将图片 转换成二进制数据
            let imageData = UIImagePNGRepresentation(self.pictureController.imageList.last!)
            HTTPClient.sharedClient.POST(urlString, parameters: parameters, constructingBodyWithBlock: { (formData) -> Void in
                //将需要上传的文件转换为为二进制数据，拼接到formData中
                
                //data : 需啊哟上传的文件的二进制数据
                //name:服务器接受字段
                //fileName：服务器存储文件的名字，随便洗，服务器会自己重新命名
                //mimeType： 文件格式，application/octet-stream 是八进制流，任意文件都可以
                //图片的文件格式：/image/jpg
                
                /*
                //微博接口值允许上传单张图片，多嚣张图片是高级接口
                //多张图片上传方法
                var index = 0
                for image in self.pictureController.imageList{
                    let imageData = UIImagePNGRepresentation(image)
                formData.appendPartWithFileData(imageData!,name:"pic",fileName:"**&&*&\(index)",mimeType:"/image/ipg")
                    index++
                }*/
                formData.appendPartWithFileData(imageData!,name:"pic",fileName:"**&&*&",mimeType:"application/octet-stream")
                }, progress: nil, success: { (_, result) -> Void in
                    print(result)
                    //回到首页
                    SVProgressHUD.showErrorWithStatus("发布成功")
                    self.close()
                }, failure: { (_, error) -> Void in
                    print(error)
            })
        
        }else{

            HTTPClient.sharedClient.requestJSONDict(.POST, urlString: urlString, parameters: parameters) { (dict, error) -> () in
                if error != nil{
                    SVProgressHUD.showErrorWithStatus("微博发布失败")
                    return
                }
                
                //发送成功
                print(dict)
                //执行关闭，返回首页
                self.close()
            }
        }
        
    }
    
    ///添加站位文本视图
    private func setTextView(){
        //添加子控件，设置约束
        view.addSubview(textView)
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(view.snp_top)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.height.equalTo(ScreenHeight/3)
        }
        //            填加占位文本
        textView.addSubview(placeHolder)
        placeHolder.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView.snp_top).offset(8)
            make.left.equalTo(textView.snp_left).offset(5)
        }
    }
    

    
    ///添加工具条
    private func setToolBar(){
        view.addSubview(toolBar)
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(view.snp_bottom)
            make.height.equalTo(40)
        }
        
        ///添加内部控件
        //按钮数组
        var items = [UIBarButtonItem]()
        //actionName对应的点击事件
        let itemSetings = [["imageName": "compose_toolbar_picture","actionName": "selectPicture"],["imageName": "compose_mentionbutton_background"],["imageName": "compose_trendbutton_background"],["imageName": "compose_emoticonbutton_background", "actionName": "selectEmoticon"],["imageName": "compose_add_background"]]
        
        for item in itemSetings{
        
            let btn = UIButton(backImageName: nil, imageName: item["imageName"]!)
            //为有点击事件名的按钮绑定点击事件
            if let actionName = item["actionName"]{
               btn.addTarget(self, action: Selector(actionName), forControlEvents: .TouchUpInside )
            }
            let barItem = UIBarButtonItem(customView: btn)
            //添加到按钮数组中
            items.append(barItem)
            //添加弹簧
            let spaceBtn = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            items.append(spaceBtn)
        }
        //移除最后一个弹簧
        items.removeLast()
        
        toolBar.items = items
        
    }
    
    func selectPicture(){
        //更新图片视图的高度
        pictureController.view.snp_updateConstraints { (make) -> Void in
            make.height.equalTo(ScreenHeight/3*2)
        }
        //更新视图
        UIView.animateWithDuration(0.25) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    func selectEmoticon(){
        print(__FUNCTION__)
    }

}

//遵守 textView的代理，当textView文本内容发生改变时，做操作
extension PublishViewController :UITextViewDelegate{
    func textViewDidChange(textView: UITextView) {
        //隐藏站位label，设置发布按钮可交互
        placeHolder.hidden = textView.hasText()
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
    }
}

